/**
 * Created by zhangsong on 2019-05-08.
 */
import React, { Component, Fragment } from 'react';
import { Button, Table, Popconfirm, Tooltip, Modal, DatePicker } from 'antd';
import { formatMessage } from '@/utils/i18n';
import { connect } from 'dva';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Pagination, gender } from '@/constants/styleConfig';
import Authorized from '@/utils/Authorized';
import { TemporaryApplication } from '@/constants/routes';
import TemporaryReducer from '@/dva/application/temporary';
import PDF from '@/components/PDFPreview';
import Power from '@/constants/power';
import ReaderCard from '@/components/ReaderCard/contractorIndex';
import moment from 'moment';
import UserReducer from '@/dva/user';
import _ from 'lodash';
// import { downloadCsv } from '@/utils/download/downloadCsv';

import Search from './search';

const { Namespace, Effects } = TemporaryReducer;

@connect(
  state => ({
    contractorStore: state[Namespace],
    userStore: state[UserReducer.Namespace],
  }),
  dispatch => ({
    handleQuery: data =>
      dispatch({
        type: `${Namespace}/${Effects.listByParam}`,
        data,
      }),
    removeById: data =>
      dispatch({
        type: `${Namespace}/${Effects.removeById}`,
        data,
      }),
    getPreviewPdfById: id =>
      dispatch({
        type: `${Namespace}/${Effects.getPreviewPdfById}`,
        data: {
          id,
        },
      }),
    handPDFModalCancel: () =>
      dispatch({
        type: `${Namespace}/${Effects.handPDFModalCancel}`,
        data: {},
      }),
    handleApproval: data =>
      dispatch({
        type: `${Namespace}/${Effects.approval}`,
        data,
      }),
    handleDisapproval: data =>
      dispatch({
        type: `${Namespace}/${Effects.disapproval}`,
        data,
      }),
    downLoadXlsx: () =>
      dispatch({
        type: `${Namespace}/${Effects.downLoadXlsx}`,
        data: {},
      }),
    openCallModal: data =>
      dispatch({
        type: `${Namespace}/${Effects.openCallModal}`,
        data,
      }),
    updateCallDate: data =>
      dispatch({
        type: `${Namespace}/${Effects.updateCallDate}`,
        data,
      }),
    getLoction(data) {
      dispatch({
        type: `${Namespace}/${Effects.getLoction}`,
        data,
      });
    },
    outById: data =>
      dispatch({
        type: `${Namespace}/${Effects.outById}`,
        data,
      }),
  }),
)
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      readerCardModal: false,
      record: null,
      calldate: undefined,
      messdate: null,
      qrcodeimg: '',
      qrcodemodal: false,
    };
  }

  componentDidMount() {
    const { handleQuery, getLoction, form, userStore = {} } = this.props;
    const { currentUser = {} } = userStore;
    console.log('222222', currentUser)
    handleQuery({
      query: {
        is_expire: 2,
      },
    });
    getLoction({ form });
  }

  openRegisterEface = record => {
    this.setState({
      readerCardModal: true,
      record,
    });
  };

  onDownload = listData => {
    // downloadCsv()
    // const array = listData.map(({ surname, nameAlias }) => [surname, nameAlias])
    // downloadCsv(array, ['name', 'age'], 'test.xlsx');
    const { downLoadXlsx } = this.props;
    downLoadXlsx();
    console.log('guolaiaiuiaia', listData);
  };

  closeRegisterEface = () => {
    this.setState({
      readerCardModal: false,
      record: null,
    });
  };

  submitRegisterCard = () => {
    const { handleQuery } = this.props;
    this.setState({
      readerCardModal: false,
      record: null,
    });
    handleQuery();
  };

  onDetailClick = (text, record) => {
    const { history } = this.props;
    const { id } = record;
    history.push(`${TemporaryApplication.detail.url}?id=${id}`);
  };

  handleUpdate = (text, record) => {
    const { history } = this.props;
    const { id } = record;
    history.push(`${TemporaryApplication.modify.url}?id=${id}`);
  };

  onPreviewClick = (text, record) => {
    this.setState({
      qrcodemodal: true,
      qrcodeimg: record.recoimage,
    })
  };

  onPreviewClickSure = () => {
    const { handPDFModalCancel } = this.props;
    handPDFModalCancel();
  };

  openCancellAtion = item => {
    console.log('openCancellAtion', item, item.checked_expiry);
    const { openCallModal } = this.props;
    this.setState({
      calldate: item.checked_expiry,
      messdate: item,
    })
    openCallModal(true);
  }

  renderColumns = () => [
    {
      title: formatMessage({ id: 'applicationContractor.temporary.name' }),
      dataIndex: 'name',
    },
    {
      title: formatMessage('applicationContractor.columns.identityCard.name'),
      dataIndex: 'identityCard',
    },
    // {
    //   title: formatMessage('applicationContractor.columns.placeOfBirth.name'),
    //   dataIndex: 'placeOfBirth',
    // },
    {
      title: formatMessage('applicationContractor.columns.emergencyContactedTelephone.name'),
      dataIndex: 'tel',
    },
    {
      title: formatMessage('applicationCommon.readerCard.passno'),
      dataIndex: 'pass_numberd',
    },
    {
      title: formatMessage('applicationContractor.temporary.escorterpass'),
      dataIndex: 'escorter_pass',
    },
    {
      title: formatMessage('applicationContractor.temporary.escortername'),
      dataIndex: 'escorter_name',
    },
    {
      title: formatMessage('applicationContractor.temporary.cardType'),
      dataIndex: 'card_typestr',
    },
    {
      title: formatMessage('applicationContractor.temporary.time'),
      dataIndex: 'expire_time',
    },
    {
      title: formatMessage('button.operator'),
      key: 'operator',
      render: (text, record, index) => {
        const { contractorStore, removeById, outById } = this.props;
        const onUpdateClick = () => {
          this.handleUpdate(text, record, index);
        };
        const onDeleteClick = () => {
          removeById({
            id: record.id,
            page: contractorStore.page,
            pageSize: contractorStore.pageSize,
            query: contractorStore.query,
          });
        };
        const onOutClick = () => {
          console.log('註銷11！！1')
          outById({
            id: record.id,
            page: contractorStore.page,
            pageSize: contractorStore.pageSize,
            query: contractorStore.query,
          });
        };
        const onDetailClick = () => {
          this.onDetailClick(text, record, index);
        };
        const onPreviewClick = () => {
          this.onPreviewClick(text, record, index);
        };
        return (
          <div>
            <Tooltip title={formatMessage('button.detail')}>
              {
                record.card_type === 1 ? null : (
                  <Button
                    className="recovery"
                    htmlType="button"
                    size="small"
                    onClick={onDetailClick}
                    icon="eye"
                  />
                )
              }

            </Tooltip>
            {
              record.card_type === 1 ? null : (
                <Authorized authority={Power.TemporaryApplication.modify}>
                  <Tooltip title={formatMessage('button.update')}>
                    <Button
                      className="recovery"
                      htmlType="button"
                      type="dashed"
                      size="small"
                      onClick={onUpdateClick}
                      icon="edit"
                    />
                  </Tooltip>
                </Authorized>
              )
            }
            <Fragment>
              <Authorized authority={Power.TemporaryApplication.remove}>
                <Popconfirm
                  title={formatMessage({ id: 'baseInfo.askDeleteRecord' })}
                  onConfirm={onDeleteClick}
                  okText={formatMessage({ id: 'button.sure' })}
                  cancelText={formatMessage({ id: 'button.cancel' })}
                >
                  <Tooltip title={formatMessage('button.remove')}>
                    <Button htmlType="button" type="danger" size="small" href="#" icon="delete" />
                  </Tooltip>
                </Popconfirm>
              </Authorized>
            </Fragment>
            <Authorized authority={Power.TemporaryApplication.preview}>
              <Tooltip title={formatMessage({ id: 'applicationContractor.temporary.qrcode' })}>
                <Button htmlType="button" size="small" onClick={onPreviewClick} icon="file-image" />
              </Tooltip>
            </Authorized>
            {/* <Authorized authority={Power.TemporaryApplication.cancellation}>
              <Button
                htmlType="button"
                type="dashed"
                size="small"
                onClick={() => this.openCancellAtion(record)}
              >
                {formatMessage('applicationCommon.readerCard.cancellAtion')}
              </Button>
            </Authorized> */}
            <Fragment>
              <Authorized authority={Power.TemporaryApplication.remove}>
                <Popconfirm
                  title={formatMessage({ id: 'applicationContractor.temporary.record' })}
                  onConfirm={onOutClick}
                  okText={formatMessage({ id: 'button.sure' })}
                  cancelText={formatMessage({ id: 'button.cancel' })}
                >
                  <Tooltip title={formatMessage('applicationCommon.readerCard.cancellAtion')}>
                    <Button
                      htmlType="button"
                      type="dashed"
                      size="small"
                    >
                      {formatMessage('applicationCommon.readerCard.cancellAtion')}
                    </Button>
                  </Tooltip>
                </Popconfirm>
              </Authorized>
            </Fragment>
          </div>
        );
      },
    },
  ];

  onChange = pagination => {
    const { current, pageSize } = pagination;
    const { handleQuery, contractorStore } = this.props;
    const { query } = contractorStore;
    handleQuery({
      query,
      page: current,
      pageSize,
    });
  };

  onCallDate = (date, dateString) => {
    console.log('date, dateString', date, dateString);
    this.setState({
      calldate: dateString == null ? undefined : dateString,
    })
  }

  onOkDate = () => {
    if (!this.state.calldate) {
      return
    }
    const { messdate, calldate } = this.state;
    const { updateCallDate, contractorStore } = this.props;
    const data = {
      update: {
        surname: _.get(messdate, 'surname', null),
        id: messdate.id,
        pass_numbered: _.get(messdate, 'pass_numbered', null),
        checked_expiry: calldate,
      },
      pagesize: {
        page: contractorStore.page,
        pageSize: contractorStore.pageSize,
      },
    }
    console.log('看看這個時間', calldate);
    updateCallDate(data)
  }

  render() {
    const { contractorStore = {}, openCallModal } = this.props;
    const {
      pageSize,
      page,
      listData,
      total,
      listLoading,
      pdfLoading,
      pdfReview,
      pdfPreviewVisible,
      callMadal,
    } = contractorStore;
    const { readerCardModal, record, calldate, qrcodeimg, qrcodemodal } = this.state;
    const defvalue = calldate ? moment(calldate, 'YYYY-MM-DD') : undefined;
    const pagination = Pagination({
      page,
      pageSize,
      total,
    });
    return (
      <PageHeaderWrapper>
        <Search onDownload={() => this.onDownload(listData)} />
        <Modal
          title={formatMessage('applicationCommon.readerCard.cancellAtion')}
          visible={callMadal}
          onCancel={() => {
            openCallModal(false);
          }}
          onOk={this.onOkDate}
        >
          <div>
            {/* <span style={{ marginRight: 10 }}>{`${formatMessage('applicationCommon.readerCard.cancellAtionDate')}:`}</span> */}
          </div>
        </Modal>
        <Modal
          title=""
          visible={qrcodemodal}
          onCancel={() => {
            this.setState({
              qrcodemodal: false,
            })
          }}
          onOk={() => this.setState({
            qrcodemodal: false,
          })}
        >
          <div>
            <img
              src={
                qrcodeimg
              }
            // width={104}
            // height={104}
            />
          </div>
        </Modal>
        {readerCardModal ? (
          <ReaderCard
            record={record}
            cancel={this.closeRegisterEface}
            sure={this.submitRegisterCard}
          />
        ) : null}
        <Table
          loading={!!listLoading}
          rowKey="id"
          columns={this.renderColumns()}
          dataSource={listData}
          onChange={this.onChange}
          pagination={pagination}
        />
      </PageHeaderWrapper>
    );
  }
}

export default Index;
